﻿namespace TestWIP
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Xml;
    using System.Xml.XPath;

    using com.crownpack.Extensions.AssemblyExtensions;
    using com.crownpack.Extensions.SharePointExtensions;

    using Microsoft.SharePoint;

    public class Class1
    {
        #region Fields

        const string SITECOLUMNS = "CalculatedColumns.xml";

        Dictionary<string, Guid> _cache;

        #endregion Fields

        #region Properties

        Dictionary<string, Guid> cache
        {
            get
            {
                if ( _cache == null )
                    _cache = new Dictionary<string, Guid>( );
                return _cache;
            }
        }

        #endregion Properties

        #region Methods

        public void Format( )
        {
            XmlNodeList fieldDefinitions = GetFieldDefinitionsAsXml( SITECOLUMNS );
            foreach ( XmlNode fieldDefinition in fieldDefinitions )
            {
                XmlNode definition = fieldDefinition.CloneNode( true );
                XmlNodeList fieldRefs = definition.SelectNodes( "//FieldRef" );
                if ( fieldRefs.Count > 0 )
                    foreach ( XmlNode fieldRef in fieldRefs )
                    {
                        if ( fieldRef.Attributes.Count > 0 )
                        {
                            string name = fieldRef.Attributes[ "Name" ].Value;
                            Guid? id = getFieldId( name );
                            if ( id.HasValue )
                                fieldRef.Attributes[ "ID" ].Value = id.Value.ToString( "B" );
                        }
                    }
                CreateSiteColumn( definition );
            }
        }

        internal XmlNodeList GetFieldDefinitionsAsXml( string resource )
        {
            XmlNodeList fields = null;
            string s = Assembly.GetExecutingAssembly( ).GetFullyQualifiedManifestResourceName( resource );
            string xml = Assembly.GetExecutingAssembly( ).GetManifestResourceAsString( s );
            if ( !string.IsNullOrEmpty( xml ) )
            {
                XmlDocument d = new XmlDocument( );
                d.LoadXml( xml );
                XmlNode n = d.SelectSingleNode( "Fields" );
                fields = n.SelectNodes( "Field" );
            }
            return fields;
        }

        protected void CreateSiteColumn( XmlNode field )
        {
            using ( SPSite spSite = new SPSite( "http://win-pv542842fga:8888/sites/crownwip" ) )
            {
                using ( SPWeb spWeb = spSite.OpenWeb( ) )
                {
                    XmlAttribute a = field.Attributes[ "StaticName" ];
                    if ( a != null )
                    {
                        string staticName = a.Value;
                        if ( !spWeb.Fields.ContainsFieldWithStaticName( staticName ) )
                        {
                            string s = field.OuterXml;
                            spWeb.Fields.AddFieldAsXml( s );
                            //SiteColumnCreated.TryRaise( new SiteColumnDefnEventArgs( staticName ) );
                        }
                        //else
                        ////SiteColumnNotCreated.TryRaise( new SiteColumnDefnEventArgs( staticName, string.Format( "Specified column already exists within {0} ({1}).", spWeb.Title, spWeb.Url ) ) );
                    }
                }
            }
        }

        void addToCache( string staticName )
        {
            using ( SPSite spSite = new SPSite( "http://win-pv542842fga:8888/sites/crownwip" ) )
            {
                using ( SPWeb spWeb = spSite.OpenWeb( ) )
                {
                    SPField spField = spWeb.Fields.TryGetFieldByStaticName( staticName );
                    if ( spField != null )
                        cache.Add( staticName, spField.Id );
                }
            }
        }

        Guid? getFieldId( string staticName )
        {
            if ( !cache.ContainsKey( staticName ) )
                addToCache( staticName );

            if ( cache.ContainsKey( staticName ) )
                return cache[ staticName ];
            else
                return null;
        }

        #endregion Methods
    }
}